package com.gradecak.alfresco.mvc.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.model.FileFolderUtil;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.namespace.QName;
import org.springframework.beans.factory.annotation.Autowired;

public class AlfrescoUtil {

  @Autowired
  private ServiceRegistry serviceRegistry;

  private NodeRef companyHomeRef;

  public NodeRef getCompanyHomeRef() {
    if (companyHomeRef != null) {
      return companyHomeRef;
    }

    ResultSet resultSet = serviceRegistry.getSearchService().query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_LUCENE,
        "PATH:\"/app:company_home\"");

    if (resultSet == null || resultSet.length() < 1) {
      throw new RuntimeException("There is no company home space");
    }
    else {
      companyHomeRef = resultSet.getNodeRef(0);
      return companyHomeRef;
    }
  }

  public void setServiceRegistry(ServiceRegistry serviceRegistry) {
    this.serviceRegistry = serviceRegistry;
  }

  public static String escapeQName(QName qName) {
    String string = qName.toString();
    return escape(string);
  }

  public static String escape(String string) {
    final int numOfCharsToAdd = 4;

    StringBuilder buf = new StringBuilder(string.length() + numOfCharsToAdd);
    for (int i = 0; i < string.length(); i++) {
      char character = string.charAt(i);
      if ((character == '{') || (character == '}') || (character == ':') || (character == '-')) {
        buf.append('\\');
      }

      buf.append(character);
    }
    return buf.toString();
  }

  public NodeRef createFolderPath(NodeRef rootSpace, List<String> pathList) {
    NodeRef containerRef = FileFolderUtil.makeFolders(this.serviceRegistry.getFileFolderService(), rootSpace, pathList, ContentModel.TYPE_FOLDER)
        .getNodeRef();

    return containerRef;
  }

  public Map<String, Serializable> convertQnameMap(Map<QName, Serializable> map) {
    Map<String, Serializable> converted = new HashMap<String, Serializable>();

    if (map != null) {
      for (Entry<QName, Serializable> entry : map.entrySet()) {
        String prefixString = entry.getKey().getPrefixedQName(serviceRegistry.getNamespaceService()).toPrefixString();
        converted.put(prefixString.replaceAll(":", "_"), entry.getValue());
      }
    }

    return converted;
  }

}
